<template>
  <div class="app-container p-6">
    <!-- 页面标题 - 完全匹配原型设计 -->
    <div class="mb-6">
      <h1 class="text-2xl font-bold text-text-primary">仪表盘概览</h1>
      <p class="text-text-muted mt-2">欢迎回来，管理员！这是您的系统运行情况概览</p>
    </div>

    <!-- 统计卡片 - 完全匹配原型设计 -->
    <el-row :gutter="24" class="stats-section mb-6">
      <el-col :xs="24" :sm="12" :lg="6">
        <div class="stat-card">
          <div class="flex items-center justify-between mb-4">
            <h3 class="text-text-secondary font-medium">总用户数</h3>
            <div class="w-10 h-10 rounded-full bg-primary-weak flex items-center justify-center text-primary">
              <i class="fas fa-users"></i>
            </div>
          </div>
          <div class="text-3xl font-bold text-text-primary">{{ userCount }}</div>
          <div class="flex items-center mt-2 text-sm">
            <span class="text-success flex items-center"><i class="fas fa-arrow-up mr-1"></i> 8.2%</span>
            <span class="text-text-muted ml-2">较上月</span>
          </div>
        </div>
      </el-col>

      <el-col :xs="24" :sm="12" :lg="6">
        <div class="stat-card">
          <div class="flex items-center justify-between mb-4">
            <h3 class="text-text-secondary font-medium">角色数量</h3>
            <div class="w-10 h-10 rounded-full bg-info-10 flex items-center justify-center text-info">
              <i class="fas fa-user-shield"></i>
            </div>
          </div>
          <div class="text-3xl font-bold text-text-primary">{{ roleCount }}</div>
          <div class="flex items-center mt-2 text-sm">
            <span class="text-success flex items-center"><i class="fas fa-arrow-up mr-1"></i> 2</span>
            <span class="text-text-muted ml-2">较上月</span>
          </div>
        </div>
      </el-col>

      <el-col :xs="24" :sm="12" :lg="6">
        <div class="stat-card">
          <div class="flex items-center justify-between mb-4">
            <h3 class="text-text-secondary font-medium">权限总数</h3>
            <div class="w-10 h-10 rounded-full bg-success-10 flex items-center justify-center text-success">
              <i class="fas fa-lock"></i>
            </div>
          </div>
          <div class="text-3xl font-bold text-text-primary">{{ permissionCount }}</div>
          <div class="flex items-center mt-2 text-sm">
            <span class="text-success flex items-center"><i class="fas fa-arrow-up mr-1"></i> 12.5%</span>
            <span class="text-text-muted ml-2">较上月</span>
          </div>
        </div>
      </el-col>

      <el-col :xs="24" :sm="12" :lg="6">
        <div class="stat-card">
          <div class="flex items-center justify-between mb-4">
            <h3 class="text-text-secondary font-medium">在线用户</h3>
            <div class="w-10 h-10 rounded-full bg-warning-10 flex items-center justify-center text-warning">
              <i class="fas fa-eye"></i>
            </div>
          </div>
          <div class="text-3xl font-bold text-text-primary">{{ onlineCount }}</div>
          <div class="flex items-center mt-2 text-sm">
            <span class="text-danger flex items-center"><i class="fas fa-arrow-up mr-1"></i> 5.3%</span>
            <span class="text-text-muted ml-2">较上月</span>
          </div>
        </div>
      </el-col>
    </el-row>

    <!-- 图表区域 - 完全匹配原型设计 -->
    <el-row :gutter="24" class="charts-section mb-6">
      <!-- 用户登录趋势图表 -->
      <el-col :xs="24" :lg="16">
        <div class="chart-card">
          <div class="flex items-center justify-between mb-4">
            <h3 class="font-semibold text-text-primary">用户增长趋势</h3>
            <div class="flex space-x-2">
              <button class="px-3 py-1 text-sm rounded-md bg-bg-hover text-text-secondary hover:text-primary">本周</button>
              <button class="px-3 py-1 text-sm rounded-md bg-primary-weak text-primary">本月</button>
              <button class="px-3 py-1 text-sm rounded-md bg-bg-hover text-text-secondary hover:text-primary">本年</button>
            </div>
          </div>
          <div class="h-64" v-loading="loginTrendLoading">
            <div v-if="loginTrendData">
              <v-chart 
                class="login-trend-chart" 
                :option="loginTrendChartOption" 
                autoresize
              />
            </div>
            <div v-else class="empty-state">
              <el-icon :size="48" class="empty-icon"><TrendCharts /></el-icon>
              <p class="empty-text">暂无登录趋势数据</p>
            </div>
          </div>
        </div>
      </el-col>

      <!-- 权限分布统计图表 -->
      <el-col :xs="24" :lg="8">
        <div class="chart-card">
          <div class="flex items-center justify-between mb-4">
            <h3 class="font-semibold text-text-primary">权限分布统计</h3>
            <button class="text-text-muted hover:text-primary" @click="refreshPermissionDistribution">
              <i class="fas fa-sync-alt"></i>
            </button>
          </div>
          <div class="h-64" v-loading="permissionDistLoading">
            <div v-if="permissionDistData && permissionDistData.items.length > 0">
              <v-chart 
                class="permission-dist-chart" 
                :option="permissionDistChartOption" 
                autoresize
              />
            </div>
            <div v-else class="empty-state">
              <el-icon :size="48" class="empty-icon"><PieChart /></el-icon>
              <p class="empty-text">暂无权限分布数据</p>
            </div>
          </div>
        </div>
      </el-col>
    </el-row>

    <!-- 快捷操作 -->
    <el-row :gutter="24">
      <el-col :xs="24" :lg="12">
        <div class="chart-card">
          <div class="flex items-center justify-between mb-6">
            <h3 class="font-semibold text-text-primary">快捷操作</h3>
          </div>
          <div class="quick-actions-grid">
            <!-- 个人中心 - 无权限限制 -->
            <div 
              class="action-card profile-card"
              @click="$router.push('/profile')"
            >
              <div class="card-icon">
                <el-icon :size="32"><User /></el-icon>
              </div>
              <div class="card-content">
                <h4 class="card-title">个人中心</h4>
                <p class="card-desc">查看个人信息</p>
              </div>
              <div class="card-arrow">
                <el-icon><ArrowRight /></el-icon>
              </div>
            </div>
            
            <!-- 密码修改 - 无权限限制 -->
            <div 
              class="action-card password-card"
              @click="showPasswordDialog = true"
            >
              <div class="card-icon">
                <el-icon :size="32"><Lock /></el-icon>
              </div>
              <div class="card-content">
                <h4 class="card-title">修改密码</h4>
                <p class="card-desc">更新登录密码</p>
              </div>
              <div class="card-arrow">
                <el-icon><ArrowRight /></el-icon>
              </div>
            </div>
            
            <!-- 用户管理卡片 -->
            <div 
              class="action-card user-card"
              @click="$router.push('/system/user')"
              v-permission="'system:user:list'"
            >
              <div class="card-icon">
                <el-icon :size="32"><UserFilled /></el-icon>
              </div>
              <div class="card-content">
                <h4 class="card-title">用户管理</h4>
                <p class="card-desc">管理系统用户</p>
              </div>
              <div class="card-arrow">
                <el-icon><ArrowRight /></el-icon>
              </div>
            </div>
            
            <!-- 角色管理卡片 -->
            <div 
              class="action-card role-card"
              @click="$router.push('/system/role')"
              v-permission="'system:role:list'"
            >
              <div class="card-icon">
                <el-icon :size="32"><Setting /></el-icon>
              </div>
              <div class="card-content">
                <h4 class="card-title">角色管理</h4>
                <p class="card-desc">配置用户角色</p>
              </div>
              <div class="card-arrow">
                <el-icon><ArrowRight /></el-icon>
              </div>
            </div>
            
            <!-- 权限配置卡片 -->
            <div 
              class="action-card permission-card"
              @click="$router.push('/system/permission')"
              v-permission="'system:permission:list'"
            >
              <div class="card-icon">
                <el-icon :size="32"><Key /></el-icon>
              </div>
              <div class="card-content">
                <h4 class="card-title">权限配置</h4>
                <p class="card-desc">权限策略管理</p>
              </div>
              <div class="card-arrow">
                <el-icon><ArrowRight /></el-icon>
              </div>
            </div>
            
            <!-- 系统设置 - 降低权限要求 -->
            <div 
              class="action-card settings-card"
              @click="$router.push('/system/settings')"
            >
              <div class="card-icon">
                <el-icon :size="32"><Tools /></el-icon>
              </div>
              <div class="card-content">
                <h4 class="card-title">系统设置</h4>
                <p class="card-desc">系统基础配置</p>
              </div>
              <div class="card-arrow">
                <el-icon><ArrowRight /></el-icon>
              </div>
            </div>
          </div>
          
          <!-- 密码修改对话框 -->
          <el-dialog 
            v-model="showPasswordDialog" 
            title="修改密码" 
            width="400px"
            :before-close="handleClosePasswordDialog"
          >
            <el-form :model="passwordForm" :rules="passwordRules" ref="passwordFormRef" label-width="80px">
              <el-form-item label="原密码" prop="oldPassword">
                <el-input 
                  v-model="passwordForm.oldPassword" 
                  type="password" 
                  placeholder="请输入原密码"
                  show-password
                />
              </el-form-item>
              <el-form-item label="新密码" prop="newPassword">
                <el-input 
                  v-model="passwordForm.newPassword" 
                  type="password" 
                  placeholder="请输入新密码"
                  show-password
                />
              </el-form-item>
              <el-form-item label="确认密码" prop="confirmPassword">
                <el-input 
                  v-model="passwordForm.confirmPassword" 
                  type="password" 
                  placeholder="请再次输入新密码"
                  show-password
                />
              </el-form-item>
            </el-form>
            <template #footer>
              <span class="dialog-footer">
                <el-button @click="showPasswordDialog = false">取消</el-button>
                <el-button type="primary" @click="handleSubmitPassword" :loading="passwordSubmitting">
                  确定
                </el-button>
              </span>
            </template>
          </el-dialog>
        </div>
      </el-col>

      <el-col :xs="24" :lg="12">
        <div class="chart-card">
          <div class="flex items-center justify-between mb-6">
            <h3 class="font-semibold text-text-primary">系统信息</h3>
          </div>
          <div v-loading="systemInfoLoading">
            <div v-if="systemInfoData">
              <div class="flex justify-between py-3 border-b border-border">
                <span class="text-sm text-text-secondary">系统版本：</span>
                <span class="text-sm font-medium text-text-primary">{{ systemInfoData.version }}</span>
              </div>
              <div class="flex justify-between py-3 border-b border-border">
                <span class="text-sm text-text-secondary">运行环境：</span>
                <span class="text-sm font-medium text-text-primary">{{ systemInfoData.environment }}</span>
              </div>
              <div class="flex justify-between py-3 border-b border-border">
                <span class="text-sm text-text-secondary">Java版本：</span>
                <span class="text-sm font-medium text-text-primary">{{ systemInfoData.javaVersion }}</span>
              </div>
              <div class="flex justify-between py-3 border-b border-border">
                <span class="text-sm text-text-secondary">内存使用：</span>
                <span class="text-sm font-medium text-text-primary">{{ systemInfoData.memoryUsage }}</span>
              </div>
              <div class="flex justify-between py-3 border-b border-border">
                <span class="text-sm text-text-secondary">运行时长：</span>
                <span class="text-sm font-medium text-text-primary">{{ systemInfoData.uptime }}</span>
              </div>
              <div class="flex justify-between py-3 border-b border-border">
                <span class="text-sm text-text-secondary">租户模式：</span>
                <span class="text-sm font-medium text-text-primary">{{ systemInfoData.tenantEnabled ? '已启用' : '已关闭' }}</span>
              </div>
              <div class="flex justify-between py-3">
                <span class="text-sm text-text-secondary">数据库：</span>
                <span class="text-sm font-medium text-text-primary">{{ systemInfoData.databaseInfo }}</span>
              </div>
            </div>
            <div v-else>
              <div class="flex justify-between py-3 border-b border-border">
                <span class="text-sm text-text-secondary">系统版本：</span>
                <span class="text-sm font-medium text-text-primary">{{ version }}</span>
              </div>
              <div class="flex justify-between py-3 border-b border-border">
                <span class="text-sm text-text-secondary">运行环境：</span>
                <span class="text-sm font-medium text-text-primary">{{ NODE_ENV }}</span>
              </div>
              <div class="flex justify-between py-3 border-b border-border">
                <span class="text-sm text-text-secondary">租户模式：</span>
                <span class="text-sm font-medium text-text-primary">{{ tenantEnabled ? '已启用' : '已关闭' }}</span>
              </div>
              <div class="flex justify-between py-3">
                <span class="text-sm text-text-secondary">最后登录：</span>
                <span class="text-sm font-medium text-text-primary">{{ lastLoginTime }}</span>
              </div>
            </div>
          </div>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { use } from 'echarts/core'
import { LineChart, PieChart as EChartsPie } from 'echarts/charts'
import {
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent
} from 'echarts/components'
import { CanvasRenderer } from 'echarts/renderers'
import VChart from 'vue-echarts'
import { 
  User, 
  UserFilled, 
  Lock, 
  View, 
  Plus, 
  Setting, 
  Menu, 
  Key,
  TrendCharts,
  PieChart,
  Refresh,
  FolderOpened,
  Monitor,
  ArrowRight,
  Tools,
  MoreFilled
} from '@element-plus/icons-vue'
import { useUserStore } from '@/stores/user'
import { useAppStore } from '@/stores/app'
import { formatDate } from '@/utils/date'
import { dashboardApi } from '@/api/dashboard'
import type { DashboardStats } from '@/api/dashboard'

// 注册ECharts组件
use([
  LineChart,
  EChartsPie,
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent,
  CanvasRenderer
])

const userStore = useUserStore()
const appStore = useAppStore()

// 基础统计数据
const userCount = ref(0)
const roleCount = ref(0)
const permissionCount = ref(0)
const onlineCount = ref(0)
const loading = ref(false)
const dashboardData = ref<DashboardStats | null>(null)

// 图表数据类型定义
interface LoginTrendData {
  dates: string[]
  loginCounts: number[]
  uniqueUsers: number[]
}

interface PermissionDistItem {
  name: string
  value: number
}

interface PermissionDistData {
  total: number
  items: PermissionDistItem[]
}

interface SystemInfoData {
  version: string
  environment: string
  javaVersion: string
  memoryUsage: string
  uptime: string
  tenantEnabled: boolean
  databaseInfo: string
}

// 图表数据
const loginTrendData = ref<LoginTrendData | null>(null)
const loginTrendLoading = ref(false)
const permissionDistData = ref<PermissionDistData | null>(null)
const permissionDistLoading = ref(false)
const systemInfoData = ref<SystemInfoData | null>(null)
const systemInfoLoading = ref(false)

// 密码修改相关
const showPasswordDialog = ref(false)
const passwordSubmitting = ref(false)
const passwordForm = ref({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

const passwordFormRef = ref()

const passwordRules = {
  oldPassword: [
    { required: true, message: '请输入原密码', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请再次输入新密码', trigger: 'blur' },
    {
      validator: (rule: any, value: string, callback: any) => {
        if (value !== passwordForm.value.newPassword) {
          callback(new Error('两次输入密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 计算属性
const version = computed(() => dashboardData.value?.systemInfo.version || appStore.config.version || '1.0.0')
const tenantEnabled = computed(() => dashboardData.value?.systemInfo.tenantEnabled ?? appStore.config.tenantEnabled ?? false)
const lastLoginTime = computed(() => '暂无记录')

// 环境变量
const NODE_ENV = import.meta.env.NODE_ENV

// 获取基础统计数据
const getStatistics = async () => {
  try {
    loading.value = true
    
    // 调用综合Dashboard API获取所有统计数据
    const stats = await dashboardApi.getDashboardData()
    
    // 更新响应式数据
    dashboardData.value = stats
    userCount.value = stats.userCount
    roleCount.value = stats.roleCount
    permissionCount.value = stats.permissionCount
    onlineCount.value = stats.onlineCount
    
    console.log('获取Dashboard统计数据成功:', stats)
  } catch (error) {
    console.error('获取Dashboard统计数据失败:', error)
    // 保持默认值0，不抛出异常
  } finally {
    loading.value = false
  }
}

// 获取登录趋势数据
const getLoginTrend = async () => {
  try {
    loginTrendLoading.value = true
    const response = await dashboardApi.getLoginTrend()
    loginTrendData.value = response.data
    console.log('获取登录趋势成功:', response.data)
  } catch (error) {
    console.error('获取登录趋势失败:', error)
  } finally {
    loginTrendLoading.value = false
  }
}

// 获取权限分布数据
const getPermissionDistribution = async () => {
  try {
    permissionDistLoading.value = true
    const response = await dashboardApi.getPermissionDistribution()
    permissionDistData.value = response.data
    console.log('获取权限分布成功:', response.data)
  } catch (error) {
    console.error('获取权限分布失败:', error)
  } finally {
    permissionDistLoading.value = false
  }
}

// 获取系统信息
const getSystemInfo = async () => {
  try {
    systemInfoLoading.value = true
    const response = await dashboardApi.getSystemInfo()
    systemInfoData.value = response.data
    console.log('获取系统信息成功:', response.data)
  } catch (error) {
    console.error('获取系统信息失败:', error)
  } finally {
    systemInfoLoading.value = false
  }
}

// 刷新方法
const refreshLoginTrend = () => {
  getLoginTrend()
}

const refreshPermissionDistribution = () => {
  getPermissionDistribution()
}

// 密码修改处理
const handleClosePasswordDialog = () => {
  passwordFormRef.value?.resetFields()
  passwordForm.value = {
    oldPassword: '',
    newPassword: '',
    confirmPassword: ''
  }
  showPasswordDialog.value = false
}

const handleSubmitPassword = async () => {
  try {
    await passwordFormRef.value?.validate()
    passwordSubmitting.value = true
    
    // 这里调用密码修改API
    // await authApi.changePassword(passwordForm.value)
    
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    ElMessage.success('密码修改成功')
    handleClosePasswordDialog()
  } catch (error) {
    console.error('密码修改失败:', error)
    ElMessage.error('密码修改失败，请检查原密码是否正确')
  } finally {
    passwordSubmitting.value = false
  }
}

// 登录趋势图表配置
const loginTrendChartOption = computed(() => {
  if (!loginTrendData.value) return {}
  
  return {
    title: {
      text: '登录趋势分析',
      left: 'center',
      top: '3%',
      textStyle: {
        fontSize: 16,
        fontWeight: 'bold',
        color: '#303133'
      }
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross',
        label: {
          backgroundColor: '#6a7985'
        }
      },
      backgroundColor: 'rgba(50, 50, 50, 0.9)',
      borderColor: '#777',
      borderWidth: 1,
      textStyle: {
        color: '#fff'
      }
    },
    legend: {
      data: ['登录次数', '独立用户'],
      top: '12%',
      left: 'center',
      textStyle: {
        color: '#606266'
      }
    },
    grid: {
      left: '5%',
      right: '5%',
      bottom: '10%',
      top: '30%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: loginTrendData.value.dates,
      axisLine: {
        lineStyle: {
          color: '#e4e7ed'
        }
      },
      axisLabel: {
        color: '#909399'
      }
    },
    yAxis: {
      type: 'value',
      splitLine: {
        lineStyle: {
          color: '#f0f0f0',
          type: 'dashed'
        }
      },
      axisLine: {
        lineStyle: {
          color: '#e4e7ed'
        }
      },
      axisLabel: {
        color: '#909399'
      }
    },
    series: [
      {
        name: '登录次数',
        type: 'line',
        smooth: true,
        symbol: 'circle',
        symbolSize: 6,
        lineStyle: {
          width: 3,
          color: '#409EFF'
        },
        itemStyle: {
          color: '#409EFF',
          borderColor: '#409EFF',
          borderWidth: 2
        },
        areaStyle: {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [
              { offset: 0, color: 'rgba(64, 158, 255, 0.6)' },
              { offset: 1, color: 'rgba(64, 158, 255, 0.1)' }
            ]
          }
        },
        data: loginTrendData.value.loginCounts
      },
      {
        name: '独立用户',
        type: 'line',
        smooth: true,
        symbol: 'circle',
        symbolSize: 6,
        lineStyle: {
          width: 3,
          color: '#67C23A'
        },
        itemStyle: {
          color: '#67C23A',
          borderColor: '#67C23A',
          borderWidth: 2
        },
        data: loginTrendData.value.uniqueUsers
      }
    ]
  }
})

// 权限分布图表配置
const permissionDistChartOption = computed(() => {
  if (!permissionDistData.value || permissionDistData.value.items.length === 0) return {}
  
  const chartData = permissionDistData.value.items.map(item => ({
    name: item.name,
    value: item.value,
    itemStyle: {
      color: getPermissionColor(item.name)
    }
  }))
  
  return {
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)',
      backgroundColor: 'rgba(50, 50, 50, 0.9)',
      borderColor: '#777',
      borderWidth: 1,
      textStyle: {
        color: '#fff'
      }
    },
    legend: {
      orient: 'horizontal',
      bottom: '5%',
      left: 'center',
      textStyle: {
        color: '#606266',
        fontSize: 12
      },
      itemGap: 20,
      itemWidth: 14,
      itemHeight: 14
    },
    series: [
      {
        name: '权限分布',
        type: 'pie',
        radius: ['40%', '65%'],
        center: ['50%', '50%'],
        avoidLabelOverlap: true,
        itemStyle: {
          borderRadius: 6,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: true,
          position: 'outside',
          formatter: '{d}%',
          fontSize: 11,
          color: '#303133',
          distanceToLabelLine: 5
        },
        emphasis: {
          itemStyle: {
            shadowBlur: 8,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.3)'
          },
          scale: true,
          scaleSize: 3
        },
        labelLine: {
          show: true,
          length: 8,
          length2: 5,
          smooth: false,
          lineStyle: {
            width: 1
          }
        },
        data: chartData,
        animationType: 'scale',
        animationEasing: 'elasticOut',
        animationDelay: function (idx: number) {
          return Math.random() * 200
        }
      }
    ]
  }
})

// 获取权限颜色
const getPermissionColor = (name: string): string => {
  const colors: Record<string, string> = {
    '操作权限': '#409EFF',
    '资源权限': '#67C23A', 
    '接口权限': '#E6A23C',
    '其他权限': '#F56C6C'
  }
  return colors[name] || '#909399'
}

// 生命周期
onMounted(() => {
  getStatistics()
  getLoginTrend()
  getPermissionDistribution()
  getSystemInfo()
})
</script>

<style lang="scss" scoped>
// 仪表板页面专用样式 - 所有样式已迁移到全局样式文件中
// 位置：src/styles/index.scss 中的 Dashboard 样式部分
</style>
